//
//  TableViewController.m
//  simple-code-oc
//
//  Created by iGaven on 2023/12/12.
//

#import "TableViewController.h"
#import "LoadImageOperation.h"
#import "ImageModel.h"

@interface TableViewController ()

@property(nonatomic, strong) NSMutableArray *dataList;
@property(nonatomic, strong) NSOperationQueue *operationQueue;

@end

@implementation TableViewController

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (NSOperationQueue *)operationQueue {
    if (!_operationQueue) {
        _operationQueue = [[NSOperationQueue alloc] init];
        _operationQueue.maxConcurrentOperationCount = 1;
    }
    return _operationQueue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"cell"];
    
    NSArray *imgUrls = @[@"https://upload-images.jianshu.io/upload_images/29332345-2d15364c3c178468.jpg",
    @"https://upload-images.jianshu.io/upload_images/29432633-a0a33c7a9b478058.jpeg",
    @"https://upload-images.jianshu.io/upload_images/6659597-53391eb1b17895a3.jpg",
    @"https://upload-images.jianshu.io/upload_images/7615803-38178ad021e7e37d.jpg"];
    
    for (NSString *val in imgUrls) {
        ImageModel *model = [[ImageModel alloc] init];
        model.imgUrl = val;
        [self.dataList addObject:model];
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
  
    if (indexPath.row < self.dataList.count) {
        ImageModel *model = self.dataList[indexPath.row];
        if (model.image) {
            cell.imageView.image = model.image;
        } else {
            LoadImageOperation *operation = [[LoadImageOperation alloc] init];
            operation.imgUrl = model.imgUrl;
            operation.completionBlock = ^{
                [NSOperationQueue.mainQueue addOperationWithBlock:^{
                    model.image = operation.image;
                    [tableView reloadData];
                }];
            };
            [self.operationQueue addOperation:operation];
            model.operation = operation;
        }
    }
    return cell;
}



@end
